import { Component, ChangeDetectorRef, Host } from '@angular/core';
import { ResearchRiskRatingService } from './researchRiskRating.service';
import { environment } from '../../../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { UtilsService } from '../../../shared/services/utils.service';
import { ClusterComponent } from '../riskCluster/cluster.component';
import { ClusterModelWrapper } from '../riskCluster/cluster.model';
import { AnalyticsService } from '../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../shared/models/googleAnalytics.model';
import { AppComponent } from '../../../app.component';
import * as $ from 'jquery';
import { ClusterService } from '../riskCluster/cluster.service';
import { Router } from '@angular/router';
import { StorageService } from '../../../shared/services/storage.service';
import { Profile } from '../../../framework/login/models/profile.model';
import { AuthenticationService } from '../../../framework/login/login.service';

/**
 * Overall risk rating main component
 *
 * Author: Sorin Spiru, Andrei Istrate
 * Date: 13.01.2018
 */
@Component({
    moduleId: module.id,
    templateUrl: 'researchRiskRating.component.html',
    styleUrls: ['../research.component.scss', 'researchRiskRating.component.scss'],
    providers: [ResearchRiskRatingService]
})
export class ResearchRiskRartingComponent extends ClusterComponent
{
    public riskClusters: ClusterModelWrapper[];
    public riskDistribution: any[];
    public readonly resourcesUrl: string = environment.resourcesUrl;
    public ratingDistributionChartColors: { color: string; alpha: number; }[];
    public videoPart1 = 'https://globalaccess-tutorials.s3.amazonaws.com/Introducing%20Sustainalytics%20ESG%20Risk%20Rating.mp4'
    public videoPart2 = 'https://globalaccess-tutorials.s3.amazonaws.com/Sustainalytics%20ESG%20Risk%20Rating%20%20What%20makes%20the%20ESG%20Risk%20Rating%20unique.mp4';
    public videoPart3 = 'https://globalaccess-tutorials.s3.amazonaws.com/Sustainalytics%20ESG%20Risk%20Rating%20%20How%20do%20Sustainalytics%20ESG%20Risk%20Ratings%20Work.mp4';
    public currentVideo: string = this.videoPart1;
    public showTutorial: boolean = true;
    private userInfo:  Profile;

    constructor(
        private cdRef: ChangeDetectorRef,
        private riskService: ResearchRiskRatingService,
        private clusterService: ClusterService,
        private analyticsService: AnalyticsService,
        private authenticationService: AuthenticationService,
        private router: Router,
        @Host() private rootComponent: AppComponent){
        super(cdRef);
        this.ratingDistributionChartColors = [
            {color: "#175f96", alpha: 0.5}
         ];
    }

    ngOnInit() {      
        this.userInfo = StorageService.get().userInfo;
        this.showTutorial = this.userInfo.firstTimeRRUserAccepted ? !this.userInfo.firstTimeRRUserAccepted : true;
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESG RR Landing Page', 'ESG Risk Rating', {}));
        this.clusterService.getCompanyRiskClusters();
        this.clusterService.company.subscribe(clusters => {
            this.riskClusters = clusters;
            this.riskService.getCompaniesBenchmark().subscribe(data => {
                var result: any[] = []

                let maxLimit: number = Math.min(data.length, this.riskClusters[this.riskClusters.length - 1].topInterval + 1);
                let currentIndex = 0;
                for (var i = 0; i < this.riskClusters.length; i++) {
                    for (var j = currentIndex; j < maxLimit; j++) {
                        if (data[j].xValue <= this.riskClusters[i].topInterval) {
                            result.push({
                            score: data[j].xValue,
                            primary: data[j].yValue,
                            color: this.riskClusters[i].color,
                            });
                        }
                        else {
                            currentIndex = j;
                            break;
                        }
                    }
                }

                let groupedData = UtilsService.aggregateDataByRiskCluster(this.riskClusters, data, 'universe');
                this.riskDistribution = groupedData;
                if(!this.productPermissions.riskrating) this.rootComponent.finishLoading();
            });
        });
    }

    public play(video: any): void {
        video.play();
    }

    public stop(video: any): void {
        video.pause();
        video.currentTime = 0;
    }

    public downloadFile(file) {
        window.open(file, '_blank');
    }

    public getVideoImage( video: string, thumbnail = true ): string {
        const imageUrl = '/assets/img/risk';
        const size = thumbnail ? 'small' : 'large';
        switch (video) {
            case this.videoPart1:
                return `${imageUrl}/video_tutorial1_${size}.jpg`;
            case this.videoPart2:
                return `${imageUrl}/video_tutorial2_${size}.jpg`;
            case this.videoPart3:
                return `${imageUrl}/video_tutorial3_${size}.jpg`;
        }
    }

    public toggleTutorial(): void {
        if(!this.userInfo.firstTimeRRUserAccepted){
            this.authenticationService.acceptFirstTimeRRUser(this.userInfo.email).subscribe(_ => {});
            this.userInfo.firstTimeRRUserAccepted = true;
            StorageService.get().setProfile(this.userInfo);
        }
        this.showTutorial = !this.showTutorial;
    }
}
